package cn.itsource.controller;

import cn.itsource.basic.annotation.Repeat;
import cn.itsource.basic.domain.AjaxResult;
import cn.itsource.domain.user.User;
import cn.itsource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {
    @Autowired
    @Qualifier("UserServiceImpl")
    UserService userService;

    @GetMapping("user/findOne/{id}")
    public User findOne(@PathVariable Long id){
        return null;
    }
    /**
     * 手机号注册的接口
     * @param user
     * @return
     */
    @PostMapping("user/phoneRegister")
    public AjaxResult<User> phoneRegister(@RequestBody @Validated(User.PhoneRegister.class) User user){
        userService.insert(user);
        return AjaxResult.me ();
    }
    /**
     * 手机号校验
     * url:/user/checkphone/"+this.user.phone
     * 参数:String phone 在路径上
     * 返回值:AjaxResult
     */
    @GetMapping("user/checkphone/{phone}")
    public AjaxResult checkPhone(@PathVariable("phone") String phone){
        userService.checkPhone(phone);
        //System.out.println(phone);
        return AjaxResult.me ();
    }
    /**
     * url:/user/sendmobilecode/"+this.user.phone
     * 参数:String phone 在路径上
     * 返回值:AjaxResult
     */
    @Repeat(value = 5)
    @GetMapping("user/sendmobilecode/{phone}")
    public AjaxResult sendPhoneCode(@PathVariable("phone")String phone, HttpServletRequest request){

        //如果当前redis 存在该key,说明一分钟内该用户已经请求该接口,所以不能重复提交
        //request.getRemoteAddr () 获取用户ip 127.0.0.1
//        //request.getRequestURI() 获取 用户访问的url user/sendmobilecode
////        if (redisService.hasKey (request.getRemoteAddr ()+request.getRequestURI())){
////            throw new RuntimeException ("哥哥,你太快了");
////        }
////        //将该用户ip存入
////        redisService.setStringKeyAndValue (request.getRemoteAddr ()+request.getRequestURI(), request.getRemoteAddr (),1);
        //走正常业务逻辑
        userService.sendPhoneCode(phone);
        return AjaxResult.me ();
    }
}
